﻿using MySqlConnector;
using System.Text.RegularExpressions;
using System.Net.Sockets;
using System.Net;
public class DBManager
{
    public static MySqlConnection mysql = new MySqlConnection();
    public static bool Connect(string database, string server, int port, string user, string password)
    {
        mysql.ConnectionString = string.Format("database={0};server={1};port={2};user={3};password={4};", database, server, port, user, password);
        try
        {
            mysql.Open();
            return true;
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
            return false;
        }
    }
    public static bool IsSafeString(string str)
    {
        if (string.IsNullOrEmpty(str))
            return false;
        return !Regex.IsMatch(str, @"[-|;|,|.|\/|\(|\)|\{|\}|%|@|\*|!|\'|]");
    }
    public static bool IsAccountExist(string user)
    {
        if (!IsSafeString(user))
            return false;
        try
        {
            string str = string.Format("select * from account where name = '{0}'", user);
            MySqlCommand cmd = new MySqlCommand(str, mysql);
            MySqlDataReader reader = cmd.ExecuteReader();
            bool has = reader.HasRows;
            reader.Close();
            return has;
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
            return false;
        }
    }
    public static bool Register(string user, string password)
    {
        if (!IsSafeString(user) || !IsSafeString(password))
            return false;
        if (IsAccountExist(user))
            return false;
        try
        {
            string str = string.Format("insert into account set name='{0}', password='{1}'", user, password);
            MySqlCommand cmd = new MySqlCommand(str, mysql);
            MySqlDataReader reader = cmd.ExecuteReader();
            reader.Close();
            return true;
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
            return false;
        }
    }

    public static bool Login(string user, string password)
    {
        if (!IsSafeString(user) || !IsSafeString(password))
            return false;
        try
        {
            string str = string.Format("select * from account where name = '{0}' and password='{1}'", user, password);
            MySqlCommand cmd = new MySqlCommand(str, mysql);
            MySqlDataReader reader = cmd.ExecuteReader();
            bool has = reader.HasRows;
            reader.Close();
            return has;
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
            return false;
        }
    }
}


public class DBServer
{
    public static Socket socket;
    public static List<ClinetInfo> clients = new List<ClinetInfo>();
    public class ClinetInfo
    {
        public Socket socket;
        public byte[] buffer = new byte[1024];
        public ClinetInfo(Socket socket)
        {
            this.socket = socket;
        }
    }

    public static void Main(string[] argv)
    {
        try
        {
            DBManager.Connect("Day2", "124.221.109.217", 3306, "jason", "123456");
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket.Bind(new IPEndPoint(IPAddress.Any, 10010));
            socket.Listen(0);
            socket.BeginAccept(AcceptCallback, socket);
            Console.ReadLine();
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
        }
    }
    public static void AcceptCallback(IAsyncResult result)
    {
        try
        {
            Socket socket = (Socket)result.AsyncState;
            Socket client = socket.EndAccept(result);
            ClinetInfo info = new ClinetInfo(client);
            clients.Add(info);
            client.BeginReceive(info.buffer, 0, 1024, 0, ReceiveCallback, info);
            socket.BeginAccept(AcceptCallback, socket);
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
        }
    }
    public static void ReceiveCallback(IAsyncResult result)
    {
        try
        {
            ClinetInfo info = (ClinetInfo)result.AsyncState;
            int count = info.socket.EndReceive(result);

            if (count == 0)
            {
                info.socket.Close();
                clients.Remove(info);
                Console.WriteLine("one client left");
                return;
            }

            string message = System.Text.Encoding.UTF8.GetString(info.buffer, 0, count);
            string[] argv = message.Split('|');//xxxx|xxxx|xxxx
            if (argv[0] == "Register")
            {
                if (DBManager.Register(argv[1], argv[2]))
                {
                    info.socket.Send(System.Text.Encoding.UTF8.GetBytes("注册成功！"));
                }
                else
                {
                    info.socket.Send(System.Text.Encoding.UTF8.GetBytes("注册失败！"));
                }
            }
            if (argv[0] == "Login")
            {
                if (DBManager.Login(argv[1], argv[2]))
                {
                    info.socket.Send(System.Text.Encoding.UTF8.GetBytes("登录成功！"));
                }
                else
                {
                    info.socket.Send(System.Text.Encoding.UTF8.GetBytes("登录失败！"));
                }
            }

            info.socket.BeginReceive(info.buffer, 0, 1024, 0, ReceiveCallback, info);
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
        }
    }
}